package com.chzc.fm.duotin.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HttpsURLConnection;


/**
 *
 * 用HttpURLConnection封装的网络请求
 *
 * Created by BillSinla on 2016/6/7.
 */
public class HttpUtil {


    private static final String TAG = "HttpUtil";


    /**
     * GET请求
     *
     * @return
     * */
    public static Object doGet(String httpUrl){

        LogUtil.w("doGet: "+"发送请求");
        InputStream inputStream =null;
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;

        try {
            URL url = new URL(httpUrl);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("GET");
            //读取超时
            conn.setReadTimeout(5000);
            //连接超时
            conn.setConnectTimeout(5000);
            //建立连接
            conn.connect();

            int responseCode = conn.getResponseCode();
            //如果请求成功
            if(responseCode == HttpsURLConnection.HTTP_OK){
                //获取输入流
                inputStream = conn.getInputStream();
                //用来存储读取的一行字符
                String read = null;

                //封装流操作
                reader = new InputStreamReader(inputStream);
                bufferedReader = new BufferedReader(reader);

                StringBuffer resultBuffer = new StringBuffer();

                while ((read = bufferedReader.readLine()) != null){

                    //每读取一行把读取的内容拼接到结果集里面
                    resultBuffer.append(read);
                }

                String result = resultBuffer.toString();

                LogUtil.w("doGet: " + "请求成功" );
                LogUtil.w("doGet: " + result );
                //返回结果
                return result;

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                    reader.close();
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        LogUtil.w("doGet: " + "请求失败" );
        return null;
    }
    /**
     * GET请求
     * 
     * */
    public static Object doPost(String httpUrl, Map<String, String> params){

        LogUtil.w("doPost: " + "发送请求" );
        //先解析参数拼接成类似于 platform=2&ver=v1.2.2的结果
        
        //先把map转化成set
        Set<Map.Entry<String, String>> entrySet = params.entrySet();
        
        //获得迭代器
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        
        StringBuffer paramBuffer = new StringBuffer();
        while (iterator.hasNext()){
            Map.Entry<String, String> entry = iterator.next();
            
            //获取键名
            String key = entry.getKey();
            //拼接key
            paramBuffer.append(key);
            
            paramBuffer.append("=");
            
            //获取值
            String value = entry.getValue();
            //拼接value
            paramBuffer.append(value);
            
            paramBuffer.append("&");
        }
        
        //去掉最后的‘&’
        String paramString = paramBuffer.toString();
        paramString = paramString.substring(0, paramString.length()-1);
        //参数拼接完毕
        
        InputStream inputStream = null;
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;

        OutputStream outputStream = null;

        try {
            URL url = new URL(httpUrl);
            
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setDoInput(true);      //允许输入
            conn.setDoOutput(true);     //允许输出
            conn.setUseCaches(true);    //允许使用缓存
            
            conn.connect();
            
            //先写入参数再获取相应码
            
            //用输出流写入参数
            outputStream = conn.getOutputStream();
            outputStream.write(paramString.getBytes());
            outputStream.flush();
            
            int responseCode = conn.getResponseCode();
            if(responseCode == HttpsURLConnection.HTTP_OK){
                
                inputStream = conn.getInputStream();
                reader = new InputStreamReader(inputStream);
                bufferedReader = new BufferedReader(reader);
                
                StringBuffer resultBuffer = new StringBuffer();
                String read = null;
                
                while((read = bufferedReader.readLine()) != null){
                    resultBuffer.append(read);
                }
                
                String result = resultBuffer.toString();

                LogUtil.w("doPost: " + "请求成功" + result );
                return result;
            }
            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream != null) {
                    inputStream.close();
                    reader.close();
                    bufferedReader.close();
                }
                if(outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LogUtil.e("doPost: " + "请求失败" );
        return null;
    }
    /**
     * 下载文件
     *
     * @param httpUrl 请求URL
     * @param dir 文件路径
     * @param rename 文件名字
     *
     * */

    public static File download(String httpUrl, File dir, String rename, DuotinTask.IDownloadListener listener){

        //如果指定目录不存在，那么创建所有层级目录
        if(!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(dir, rename);

        if(file.exists()){
            if(listener != null){
                listener.onComplete(file);
            }
            return file;
        }

        InputStream inputStream =null;

        FileOutputStream fileOutputStream = null;

        try {
            URL url = new URL(httpUrl);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("GET");
            //读取超时
            conn.setReadTimeout(5000);
            //连接超时
            conn.setConnectTimeout(5000);
            //建立连接
            conn.connect();

            int responseCode = conn.getResponseCode();
            //如果请求成功
            if(responseCode == HttpsURLConnection.HTTP_OK){
                //获取输入流
                inputStream = conn.getInputStream();

                fileOutputStream = new FileOutputStream(file);

                byte[] buff = new byte[1024 * 4];

                int read = -1;

                //获取文件大小
                int length = conn.getContentLength();

                //已下载
                int download = 0;

                if(listener != null){
                    listener.start();
                }

                while((read = inputStream.read(buff)) != -1){
                    fileOutputStream.write(buff, 0, read);
                    fileOutputStream.flush();

                    download += read;

                    double d = download * 100.0 / length;

                    //取两位小数
                    //四舍五入保留小数点后两位数

                    BigDecimal bigDecimal = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);
                    float progress = bigDecimal.floatValue();

                    LogUtil.w("progress:" + progress);

                    if(listener != null){
                        listener.upgradeProgress(progress);
                    }
                }
                LogUtil.w("下载成功~");
                if (listener != null){
                    listener.onComplete(file);
                }
                return file;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        LogUtil.w("doGet: " + "请求失败" );
        if(listener != null){
            listener.onFail("下载失败~");
        }
        return null;
    }
}
